 /*
 * @author Pawel Gadecki <pidzama@gmail.com>
 * 
 */
package wydruk;

import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ujac.print.DocumentHandlerException;
import org.ujac.print.DocumentPrinter;

import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfReader;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPrintPage;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import spwodne.Wies;
import spwodne.Klient;
import spwodne.MTSpolek;
import spwodne.Spolka;
import spwodne.Info;
import spwodne.InfoS;
import spwodne.InfoW;

public class Drukarnia {

    private static String defUrl = "wydruki" + File.separator;

    public Drukarnia() {
    }

    public void drukujKlient(List<Klient> l, String url, Date d) throws Exception {
        drukujKlient(l, url, d, defUrl + "Klient_" + (new Date()).getTime() + ".pdf");
    }

    public void drukujKlientUpomnienie(List<Klient> l, String url, Date d, Float kwota) throws Exception {
        drukujKlientUpomnienie(l, url, d, kwota, defUrl + "Klient_Upomnienie_" + (new Date()).getTime() + ".pdf");
    }

    public void drukujWies(List<Wies> l, String url,boolean czyWszystkich) throws Exception {
        drukujWies(l, url, defUrl + "Miejscowosc_" + (new Date()).getTime() + ".pdf",czyWszystkich);
    }

    public void drukujSpolki(List<Spolka> s, Date from, Date to, String url) throws Exception {
        drukujSpolki(s, from, to, url, defUrl + "Spolka_" + (new Date()).getTime() + ".pdf");
    }

    public void drukujKlient(List<Klient> l, String url, Date d, String out) throws Exception {

        FileOutputStream pdfStream = new FileOutputStream(out);

        Document doc = new Document();
        PdfCopy copy = new PdfCopy(doc, pdfStream);
        doc.open();

        Date data = new Date();
        Date plusJeden = new Date();
        Date plusTrzy = new Date();
        Calendar cl = Calendar.getInstance();
        cl.setTime(d);
        cl.add(Calendar.DAY_OF_MONTH, 1);
        plusJeden = cl.getTime();
        cl.add(Calendar.MONTH, 3);
        plusTrzy = cl.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        for (Klient k : l) {

            try {

                Map m = new HashMap();
                m.put("KImie", k.getIm());
                m.put("KNazwisko", k.getNaz());
                m.put("KPesel", k.getPesel());
                m.put("KNip", k.getNip());
                m.put("KUlica", k.ulica);
                m.put("KMiejscowosc", k.miejscowosc);
                m.put("KKod", k.kod);
                m.put("KNr", k.getNr());
                m.put("KPowierzchnia", k.getPow().toString());
                m.put("KSumaNaleznosci", k.getSumaNal());
                m.put("KSumaWplat", k.getSumaWplat());
                m.put("KDoZaplaty", k.getSumaZostalo());
                m.put("KListaNaleznosci", k.getLNal());
                m.put("KListaWplat", k.getLWpl());
                m.put("KAktualnaData", data);
                m.put("KNazwaSpolki", MTSpolek.getSpolka(k.nrSp - 1).getNaz());
                m.put("KnazwaWsi", ((Wies) MTSpolek.getSpolka(k.nrSp - 1).getLWsi().get(k.nrWsi - 1)).getNaz());
                m.put("KStawka", MTSpolek.getSpolka(k.nrSp - 1).getStawka());
                m.put("KDataZaplaty", sdf.format(d));
                m.put("KBiezacaZal", k.getBiezacaZaleglosc());
                m.put("KListaZaleglych", k.getNiepusteZal());
                m.put("DataPlusJeden", sdf.format(plusJeden));
                m.put("DataPlusTrzy", sdf.format(plusTrzy));
                if (k.getNiepusteZal().size() > 2) {
                    m.put("KHeader", new Integer(25));
                } else {
                    m.put("KHeader", new Integer(85));
                }
                FileInputStream templateStream = new FileInputStream(url);

                DocumentPrinter documentPrinter = new DocumentPrinter(templateStream, m);
                documentPrinter.setXmlReaderClass("org.apache.xerces.parsers.SAXParser");

                ByteArrayOutputStream tmp = new ByteArrayOutputStream();

                documentPrinter.printDocument(tmp);
                PdfReader pr = new PdfReader(tmp.toByteArray());
                for (int i = 1; i <= pr.getNumberOfPages(); i++) {
                    copy.addPage(copy.getImportedPage(pr, i));
                }
                copy.freeReader(pr);
            } catch (DocumentHandlerException e1) {
                e1.printStackTrace();
            } catch (IOException e2) {
                e2.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        doc.close();


        File f = new File(out);
        FileInputStream fis = new FileInputStream(f);
        FileChannel fc = fis.getChannel();
        ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());



        PDFFile pdfFile = new PDFFile(bb); // Create PDF Print Page

        PDFPrintPage pages = new PDFPrintPage(pdfFile);

        // Create Print Job
        PrinterJob pjob = PrinterJob.getPrinterJob();
        PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
        pjob.setJobName(f.getName());
        Book book = new Book();
        book.append(pages, pf, pdfFile.getNumPages());
        pjob.setPageable(book);


        // Send print job to default printer
        // pjob.print();
        if (pjob.printDialog()) {
            pjob.print();
        }


    }

    public static Float round(float val) {
        double vval = (double) val * 100D;
        float tmp = Math.round(vval);
        return new Float(tmp / 100F);
    }

    public void drukujKlientUpomnienie(List<Klient> l, String url, Date d, Float koszt, String out) throws Exception {

        FileOutputStream pdfStream = new FileOutputStream(out);

        Document doc = new Document();
        PdfCopy copy = new PdfCopy(doc, pdfStream);
        doc.open();

        Date data = new Date();
        Date plusJeden = new Date();
        Date plusTrzy = new Date();
        Calendar cl = Calendar.getInstance();
        cl.setTime(d);
        cl.add(Calendar.DAY_OF_MONTH, 1);
        plusJeden = cl.getTime();
        cl.add(Calendar.MONTH, 3);
        plusTrzy = cl.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        for (Klient k : l) {

            try {

                Map m = new HashMap();
                m.put("KImie", k.getIm());
                m.put("KNazwisko", k.getNaz());
                m.put("KPesel", k.getPesel());
                m.put("KNip", k.getNip());
                m.put("KUlica", k.ulica);
                m.put("KMiejscowosc", k.miejscowosc);
                m.put("KKod", k.kod);
                m.put("KNr", k.getNr());
                m.put("KPowierzchnia", k.getPow().toString());
                m.put("KSumaNaleznosci", k.getSumaNal());
                m.put("KSumaWplat", k.getSumaWplat());
                m.put("KDoZaplaty", k.getSumaZostalo());
                m.put("KListaNaleznosci", k.getLNal());
                m.put("KListaWplat", k.getLWpl());
                m.put("KAktualnaData", data);
                m.put("KNazwaSpolki", MTSpolek.getSpolka(k.nrSp - 1).getNaz());
                m.put("KnazwaWsi", ((Wies) MTSpolek.getSpolka(k.nrSp - 1).getLWsi().get(k.nrWsi - 1)).getNaz());
                m.put("KStawka", MTSpolek.getSpolka(k.nrSp - 1).getStawka());
                m.put("KDataZaplaty", d);
                m.put("KBiezacaZal", k.getBiezacaZaleglosc());
                m.put("KListaZaleglych", k.getNiepusteZal());
                m.put("KosztUpomnienia", koszt);
                m.put("Suma", round(k.getSumaZostalo() + koszt));
                m.put("DataPlusJeden", sdf.format(plusJeden));
                m.put("DataPlusTrzy", sdf.format(plusTrzy));

                FileInputStream templateStream = new FileInputStream(url);

                DocumentPrinter documentPrinter = new DocumentPrinter(templateStream, m);
                documentPrinter.setXmlReaderClass("org.apache.xerces.parsers.SAXParser");

                ByteArrayOutputStream tmp = new ByteArrayOutputStream();

                documentPrinter.printDocument(tmp);
                PdfReader pr = new PdfReader(tmp.toByteArray());
                for (int i = 1; i <= pr.getNumberOfPages(); i++) {
                    copy.addPage(copy.getImportedPage(pr, i));
                }
                copy.freeReader(pr);
            } catch (DocumentHandlerException e1) {
                e1.printStackTrace();
            } catch (IOException e2) {
                e2.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        doc.close();


        File f = new File(out);
        FileInputStream fis = new FileInputStream(f);
        FileChannel fc = fis.getChannel();
        ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());



        PDFFile pdfFile = new PDFFile(bb); // Create PDF Print Page

        PDFPrintPage pages = new PDFPrintPage(pdfFile);

        // Create Print Job
        PrinterJob pjob = PrinterJob.getPrinterJob();
        PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
        pjob.setJobName(f.getName());
        Book book = new Book();
        book.append(pages, pf, pdfFile.getNumPages());
        pjob.setPageable(book);


        // Send print job to default printer
        // pjob.print();
        if (pjob.printDialog()) {
            pjob.print();
        }


    }

    public void drukujWies(List<Wies> l, String url, String out,boolean czyWszystkich) throws Exception {

        FileOutputStream pdfStream = new FileOutputStream(out);

        Document doc = new Document();
        PdfCopy copy = new PdfCopy(doc, pdfStream);
        doc.open();

        Date data = new Date();

        for (Wies w : l) {
            Map m = new HashMap();
            m.put("WListaKlientow", w.getLKli());
            m.put("WNazwa", w.getNaz());
            m.put("WId", w.getID());
            m.put("WSumaNaleznosci", w.ile_naleznosci);
            m.put("WSumaDoZaplaty", w.ile_zalega);
            m.put("WSumaPowierzchni", w.ile_ha);
            m.put("WAktualnaData", new Date());
            if(czyWszystkich)
                m.put("WCzyWszystkich", new Integer(1));
            else m.put("WCzyWszystkich", new Integer(0));
            try {

                FileInputStream templateStream = new FileInputStream(url);

                DocumentPrinter documentPrinter = new DocumentPrinter(templateStream, m);
                documentPrinter.setXmlReaderClass("org.apache.xerces.parsers.SAXParser");

                ByteArrayOutputStream tmp = new ByteArrayOutputStream();

                documentPrinter.printDocument(tmp);
                PdfReader pr = new PdfReader(tmp.toByteArray());
                for (int i = 1; i <= pr.getNumberOfPages(); i++) {
                    copy.addPage(copy.getImportedPage(pr, i));
                }
                copy.freeReader(pr);
            } catch (DocumentHandlerException e1) {
                e1.printStackTrace();
            } catch (IOException e2) {
                e2.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        doc.close();


        File f = new File(out);
        FileInputStream fis = new FileInputStream(f);
        FileChannel fc = fis.getChannel();
        ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());



        PDFFile pdfFile = new PDFFile(bb); // Create PDF Print Page

        PDFPrintPage pages = new PDFPrintPage(pdfFile);

        // Create Print Job
        PrinterJob pjob = PrinterJob.getPrinterJob();
        PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
        pjob.setJobName(f.getName());
        Book book = new Book();
        book.append(pages, pf, pdfFile.getNumPages());
        pjob.setPageable(book);


        // Send print job to default printer
        // pjob.print();
        if (pjob.printDialog()) {
            pjob.print();
        }


    }

    public void drukujSpolki(List<Spolka> s, Date from, Date to, String url, String out) throws Exception {







        FileOutputStream pdfStream = new FileOutputStream(out);

        Document doc = new Document();
        PdfCopy copy = new PdfCopy(doc, pdfStream);
        doc.open();

        Date data = new Date();



        List<InfoS> l = new ArrayList<InfoS>();
        Float sumasuma = 0f;
        for (Spolka sp : (List<Spolka>) MTSpolek.getLSpolek()) {
            InfoS is = new InfoS();
            is.setNaz(sp.getNaz());
            Float sumasp = 0f;
            for (Wies w : (List<Wies>) sp.getLWsi()) {
                Float sumaw = 0f;
                InfoW iw = new InfoW();
                iw.setNazwa(w.getNaz());
                for (Klient k : (List<Klient>) w.getLKli()) {
                    Float kasa = k.getSumaWplat(from, to);
                    if (kasa > 0f) {
                        Info iii = new Info();
                        iii.setKlient(k);
                        iii.setKwota(kasa);
                        iw.getLista().add(iii);
                        sumaw += kasa;
                    }
                }
                iw.setSuma(sumaw);
                is.getLista().add(iw);
                sumasp += sumaw;
            }
            is.setSuma(sumasp);
            sumasuma += sumasp;
            l.add(is);
        }

        try {

            Map m = new HashMap();
            m.put("SLista", l);
            m.put("AktualnaData", data);
            m.put("DataOd", from);
            m.put("DataDo", to);
            m.put("Suma", sumasuma);



            FileInputStream templateStream = new FileInputStream(url);

            DocumentPrinter documentPrinter = new DocumentPrinter(templateStream, m);
            documentPrinter.setXmlReaderClass("org.apache.xerces.parsers.SAXParser");

            ByteArrayOutputStream tmp = new ByteArrayOutputStream();

            documentPrinter.printDocument(tmp);
            PdfReader pr = new PdfReader(tmp.toByteArray());
            for (int i = 1; i <= pr.getNumberOfPages(); i++) {
                copy.addPage(copy.getImportedPage(pr, i));
            }
            copy.freeReader(pr);
        } catch (DocumentHandlerException e1) {
            e1.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


        doc.close();


        File f = new File(out);
        FileInputStream fis = new FileInputStream(f);
        FileChannel fc = fis.getChannel();
        ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        PDFFile pdfFile = new PDFFile(bb); // Create PDF Print Page

        PDFPrintPage pages = new PDFPrintPage(pdfFile);

        // Create Print Job
        PrinterJob pjob = PrinterJob.getPrinterJob();
        PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
        pjob.setJobName(f.getName());
        Book book = new Book();
        book.append(pages, pf, pdfFile.getNumPages());
        pjob.setPageable(book);


        // Send print job to default printer
        // pjob.print();
        if (pjob.printDialog()) {
            pjob.print();
        }






    }

    public static Drukarnia getInstance() {
        if (instance == null) {
            instance = new Drukarnia();
        }
        return instance;
    }
    private static Drukarnia instance = null;
}

